package com.itheima.service.impl;

import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.exception.MyException;
import com.itheima.service.UserService;
import org.springframework.dao.EmptyResultDataAccessException;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    private RoleDao roleDao;

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    @Override
    public List<User> list() {
        List<User> userList = userDao.findAll();
        for (User user : userList) {
            Long id = user.getId();
            List<Role> roleList = roleDao.findRolesByUid(id);
            user.setRoleList(roleList);
        }
        return userList;
    }

    @Override
    public void save(User user, Long[] roleIds) {
        Long Uid = userDao.save(user);

        roleDao.saveRoleAndUserRel(Uid, roleIds);
    }

    @Override
    public void del(Long userId) {
        roleDao.del(userId);
        userDao.del(userId);
    }

    @Override
    public User login(String username, String password) throws EmptyResultDataAccessException {
        User user = userDao.login(username, password);
        return user;
    }

    @Override
    public void show1() throws MyException {
        System.out.println("自定义异常...");
        throw new MyException();
    }
}
